//! # 认证提供者集成
//!
//! 本模块负责集成现有的认证提供者实现，而非重复实现。
//! 具体的认证提供者实现位于 rustcloud-gateway 和 rustcloud-security 中。

use rustcloud_security::prelude::*;

// 从 rustcloud-gateway 重新导出认证提供者（如果可用）
#[cfg(feature = "gateway-integration")]
pub use rustcloud_gateway::auth::{
    JwtAuthProvider as JwtProvider,
    ApiKeyAuthProvider as ApiKeyProvider,
    JwtConfig,
    ApiKeyConfig,
};

// OAuth2 和 LDAP 提供者（rustcloud-auth 独有实现）
#[cfg(feature = "oauth2")]
pub mod oauth2;

#[cfg(feature = "ldap")]
pub mod ldap;

// 重新导出主要类型
#[cfg(feature = "oauth2")]
pub use oauth2::{OAuth2Provider, OAuth2Config};

#[cfg(feature = "ldap")]
pub use ldap::{LdapProvider, LdapConfig};

/// 认证提供者工厂
pub struct AuthProviderFactory;

impl AuthProviderFactory {
    /// 根据类型创建认证提供者
    pub async fn create_provider(
        provider_type: &AuthProviderType,
        config: &serde_json::Value,
    ) -> AuthResult<Box<dyn AuthProvider>> {
        match provider_type {
            #[cfg(feature = "gateway-integration")]
            AuthProviderType::Jwt => {
                let jwt_config: JwtConfig = serde_json::from_value(config.clone())
                    .map_err(|e| AuthError::ConfigurationError(format!("Invalid JWT config: {}", e)))?;
                let provider = JwtProvider::new(jwt_config).await
                    .map_err(|e| AuthError::ConfigurationError(format!("Failed to create JWT provider: {}", e)))?;
                Ok(Box::new(provider))
            }

            #[cfg(feature = "gateway-integration")]
            AuthProviderType::ApiKey => {
                let api_key_config: ApiKeyConfig = serde_json::from_value(config.clone())
                    .map_err(|e| AuthError::ConfigurationError(format!("Invalid API Key config: {}", e)))?;
                let provider = ApiKeyProvider::with_config(api_key_config);
                Ok(Box::new(provider))
            }

            #[cfg(feature = "oauth2")]
            AuthProviderType::OAuth2 => {
                let oauth2_config: oauth2::OAuth2Config = serde_json::from_value(config.clone())
                    .map_err(|e| AuthError::ConfigurationError(format!("Invalid OAuth2 config: {}", e)))?;
                Ok(Box::new(oauth2::OAuth2Provider::new(oauth2_config)?))
            }

            #[cfg(feature = "ldap")]
            AuthProviderType::Ldap => {
                let ldap_config: ldap::LdapConfig = serde_json::from_value(config.clone())
                    .map_err(|e| AuthError::ConfigurationError(format!("Invalid LDAP config: {}", e)))?;
                Ok(Box::new(ldap::LdapProvider::new(ldap_config)?))
            }

            _ => Err(AuthError::UnsupportedOperation(
                format!("Provider type {:?} not supported or feature not enabled. Available providers require gateway-integration feature.", provider_type)
            ))
        }
    }

    /// 获取支持的认证提供者类型列表
    pub fn supported_types() -> Vec<AuthProviderType> {
        let mut types = Vec::new();

        #[cfg(feature = "gateway-integration")]
        {
            types.push(AuthProviderType::Jwt);
            types.push(AuthProviderType::ApiKey);
        }

        #[cfg(feature = "oauth2")]
        types.push(AuthProviderType::OAuth2);

        #[cfg(feature = "ldap")]
        types.push(AuthProviderType::Ldap);

        types
    }
}

/// 认证提供者注册表
pub struct AuthProviderRegistry {
    providers: std::collections::HashMap<String, Box<dyn AuthProvider>>,
}

impl AuthProviderRegistry {
    /// 创建新的注册表
    pub fn new() -> Self {
        Self {
            providers: std::collections::HashMap::new(),
        }
    }

    /// 注册认证提供者
    pub fn register(&mut self, name: String, provider: Box<dyn AuthProvider>) {
        self.providers.insert(name, provider);
    }

    /// 获取认证提供者
    pub fn get(&self, name: &str) -> Option<&dyn AuthProvider> {
        self.providers.get(name).map(|p| p.as_ref())
    }

    /// 列出所有已注册的提供者
    pub fn list_providers(&self) -> Vec<String> {
        self.providers.keys().cloned().collect()
    }

    /// 从配置文件批量注册提供者
    pub async fn register_from_config(&mut self, config: &ProvidersConfig) -> AuthResult<()> {
        for provider_config in &config.providers {
            if provider_config.enabled {
                let provider = AuthProviderFactory::create_provider(
                    &provider_config.provider_type,
                    &provider_config.config,
                ).await?;
                self.register(provider_config.name.clone(), provider);
            }
        }
        Ok(())
    }
}

impl Default for AuthProviderRegistry {
    fn default() -> Self {
        Self::new()
    }
}

/// 认证提供者配置
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ProviderConfig {
    /// 提供者名称
    pub name: String,
    /// 提供者类型
    pub provider_type: AuthProviderType,
    /// 是否启用
    pub enabled: bool,
    /// 优先级
    pub priority: i32,
    /// 具体配置
    pub config: serde_json::Value,
}

/// 多个认证提供者的配置
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ProvidersConfig {
    /// 提供者列表
    pub providers: Vec<ProviderConfig>,
    /// 默认提供者
    pub default_provider: String,
}

impl Default for ProvidersConfig {
    fn default() -> Self {
        Self {
            providers: vec![
                ProviderConfig {
                    name: "jwt".to_string(),
                    provider_type: AuthProviderType::Jwt,
                    enabled: true,
                    priority: 10,
                    config: serde_json::json!({
                        "secret": "default_jwt_secret",
                        "algorithm": "HS256",
                        "expiration_seconds": 3600
                    }),
                },
                ProviderConfig {
                    name: "api_key".to_string(),
                    provider_type: AuthProviderType::ApiKey,
                    enabled: true,
                    priority: 5,
                    config: serde_json::json!({
                        "header_name": "X-API-Key",
                        "validate_permissions": true
                    }),
                },
            ],
            default_provider: "jwt".to_string(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_auth_provider_factory_supported_types() {
        let types = AuthProviderFactory::supported_types();
        assert!(!types.is_empty());
        
        // 根据feature flags检查支持的类型
        #[cfg(feature = "gateway-integration")]
        {
            assert!(types.contains(&AuthProviderType::Jwt));
            assert!(types.contains(&AuthProviderType::ApiKey));
        }
    }

    #[test]
    fn test_auth_provider_registry() {
        let mut registry = AuthProviderRegistry::new();
        assert!(registry.list_providers().is_empty());
        
        // 这里需要具体的提供者实现才能测试注册功能
        // 测试基本的列表功能
        let providers = registry.list_providers();
        assert_eq!(providers.len(), 0);
    }

    #[test]
    fn test_providers_config_default() {
        let config = ProvidersConfig::default();
        assert_eq!(config.default_provider, "jwt");
        assert!(!config.providers.is_empty());
        
        // 检查默认配置包含JWT和API Key
        let provider_names: Vec<_> = config.providers.iter().map(|p| &p.name).collect();
        assert!(provider_names.contains(&&"jwt".to_string()));
        assert!(provider_names.contains(&&"api_key".to_string()));
    }

    #[test]
    fn test_provider_config_serialization() {
        let config = ProviderConfig {
            name: "test".to_string(),
            provider_type: AuthProviderType::Jwt,
            enabled: true,
            priority: 1,
            config: serde_json::json!({"key": "value"}),
        };

        let serialized = serde_json::to_string(&config).unwrap();
        let deserialized: ProviderConfig = serde_json::from_str(&serialized).unwrap();
        
        assert_eq!(config.name, deserialized.name);
        assert_eq!(config.provider_type, deserialized.provider_type);
        assert_eq!(config.enabled, deserialized.enabled);
        assert_eq!(config.priority, deserialized.priority);
    }
}